﻿using Microsoft.Extensions.Logging;
using TcpJsonService.Core;

namespace TcpJsonService.Fvs
{
    /// <summary>
    /// 通知字节流协议
    /// </summary>
    public class Notice
    {
        public static ushort Id => 0x0006;

        /// <summary>
        /// 控制器通道监听的端口
        /// </summary>
        [SerializeIndex(1)]
        public ushort Port { get; set; }

        /// <summary>
        /// 通知协议的字节流
        /// </summary>
        [SerializeIndex(2)] 
        public List<byte> Buffer { get; set; }

    }

    /// <summary>
    /// 通知协议通道
    /// </summary>
    public class NoticeChannel : TcpChannel
    {
        /// <summary>
        /// 控制器通道字典,键为监听端口
        /// </summary>
        private readonly Dictionary<int, FvsControllerChannel> _channels;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="port">监听端口</param>
        /// <param name="logger">日志</param>
        /// <param name="channels">控制器通道字典</param>
        public NoticeChannel(int port, ILogger logger, Dictionary<int, FvsControllerChannel> channels)
            : base(port, logger)
        {
            _channels = channels;
            foreach (var channel in _channels.Values)
            {
                channel.Noticed += NoticedEventHandler;
            }
        }

        /// <summary>
        /// 通知事件处理函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void NoticedEventHandler(object sender, GotProtocolEventArgs e)
        {
            Notice notice = new()
            {
                Port = Convert.ToUInt16(e.Port),
                Buffer = e.Buffer
            };
            List<byte> contentBuffer = ByteFormatter.Serialize(notice);
            ProtocolHead head = new()
            {
                Tag = ProtocolHead.HeadTag,
                Id = Fvs.Notice.Id,
                ContentSize = Convert.ToUInt16(contentBuffer.Count),
                TimeStamp = Convert.ToInt64((DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds)
            };
            List<byte> buffer = ByteFormatter.Serialize(head);
            buffer.AddRange(contentBuffer);
            Notice([.. buffer]);
        }
    }
}
